import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import {createPage, ajax, base} from 'nc-lightapp-front';
import {buttonClick, afterEvent, refreshButtonClick} from './events';
import initTemplate from './events/initTemPlate';
import requestApi from './requestApi';
import './index.less';
//import BusinessUnitTreeRef from 'uapbd/refer/org/BusinessUnitAndGroupTreeRef/index';
import BusinessUnitTreeRef from 'uapbd/refer/org/BusinessUnitTreeRef';
import {SyncTree} from 'ssccommon/components/tree';
import {EditTable} from 'ssccommon/components/table';
import {
    ProfileStyle,
    ProfileHead,
    ProfileBody,
    BodyLeft,
    BodyRight,
    HeadCenterCustom,
    EmptyArea,
    ButtonGroup
} from 'ssccommon/components/profile';
import pubMessage from 'ssccommon/utils/pubMessage'
import { setTable, setForm } from 'ssccommon/utils/setComponentUsed'

window.bodyCode = 'Sqdlr';//可代理人员
window.body1Code = 'SqdlDept';//可代理部门
window.body2Code = 'SqdlSpec';//特殊代理

class AuthAgentConfig extends Component{
    constructor(props) {
        super(props);
        setTable(props, 'copyModal')
        setForm(props, window.body2Code)
        this.state = {
            showRight: false,
            showModal: false,
            disableOrg : false,
            orgPk : '',
            fianceRef : {},
            disabledSearch : false,
            status : 'browse'
        };
        this.close = this.close.bind(this);
        this.pubMessage = new pubMessage();
        initTemplate.call(this, props);
    }

    componentWillMount() {
                window.onbeforeunload = () => {
                      debugger;
                    let status = this.props.editTable.getStatus(window.bodyCode);          
                    if (status == 'edit') {
                        return ''; 
                         }
             }
            }
    componentDidMount() {
        this.queryRole(null);
    }

    queryRole(pk){
        window.orgPk = pk;
        let {syncTree } = this.props;
        let { setSyncTreeData } = syncTree;
        this.setSyncTreeData = setSyncTreeData;
        requestApi.queryRole({
            data : {
                "pkOrg": pk
            },
            success: (data) => {
                if(data){
                    let dataList = [];
                    data && data.RoleList.rows.forEach((item) =>{
                        let roleObj = new Object();
                        roleObj.refpk = item.values.pk_role.value;
                        roleObj.refname = item.values.role_name.value;
                        roleObj.refcode = item.values.role_code.value;
                        roleObj.values = {};
                        dataList.push(roleObj);
                        if(!window.groupPk){
                            window.groupPk = item.values.pk_group.value
                        }
                    });
                    this.newTree = syncTree.createTreeData(dataList);   //创建树 组件需要的数据结构
                    this.setSyncTreeData('tree1',  this.newTree);
                }else{
                    this.setSyncTreeData('tree1', []);
                }
                this.props.button.setButtonsVisible({
                    "Edit" : true,
                    "Save" : false,
                    "Cancel" : false,
                    "Copy" : true,
                    "AddLine1" : false,
                    "AddLine" : false,
                });
            }
        })
    }

    copy() {
        let props = this.props;
        this.setState({ showModal: false });
        let dlrData = props.editTable.getAllData(window.bodyCode);
        let dlDeptData = props.editTable.getAllData(window.body1Code);
        let dlSpecData = props.form.getAllFormValue(window.body2Code);

        this.props.table.getCheckedRows('copyModal').forEach((item) => {
            let resultRows = [];
            //代理的人
            dlrData.rows.forEach((row) => {
                if(row.status != '3'){
                    let dlrRow = new Object();
                    dlrRow.values = {
                        'pk_roler' : {
                            'value' : item.data.values.pk_role.value
                        },
                        'keyword' : {
                            'value' : 'busiuser'
                        },
                        'pk_user' : {
                            'value' : row.values.pk_user.value
                        },
                        'pk_org' : {
                            'value' : item.data.values.pk_org.value
                        }
                    };
                    resultRows.push(dlrRow);
                }
            });
            //代理的部门
            dlDeptData.rows.forEach((row) => {
                if(row.status != '3'){
                    let deptRow = new Object();
                    deptRow.values = {
                        'pk_roler' : {
                            'value' : item.data.values.pk_role.value
                        },
                        'keyword' : {
                            'value' : 'pk_deptdoc'
                        },
                        'pk_user' : {
                            'value' : row.values.pk_user.value
                        },
                        'pk_org' : {
                            'value' : item.data.values.pk_org.value
                        }
                    };
                    resultRows.push(deptRow);
                }
            });
            //特殊代理
            dlSpecData.rows.forEach((row) => {
                if(row.values.isall){
                    let isAllRow = new Object();
                    isAllRow.values = {
                        'pk_roler' : {
                            'value' : item.data.values.pk_role.value
                        },
                        'keyword' : {
                            'value' : 'isall'
                        },
                        'pk_user' : {
                            'value' : 'true'
                        },
                        'pk_org' : {
                            'value' : item.data.values.pk_org.value
                        }
                    };
                    if (row.values.isall.value){
                        resultRows.push(isAllRow);
                    }
                }
                if(row.values.issamedept){
                    let sameDeptRow = new Object();
                    sameDeptRow.values = {
                        'pk_roler' : {
                            'value' : item.data.values.pk_role.value
                        },
                        'keyword' : {
                            'value' : 'issamedept'
                        },
                        'pk_user' : {
                            'value' : 'true'
                        },
                        'pk_org' : {
                            'value' : item.data.values.pk_org.value
                        }
                    }
                    if (row.values.issamedept.value){
                        resultRows.push(sameDeptRow);
                    }
                }
            })
            //保存
            if(resultRows.length > 0){
                let reqData = new Object();
                reqData.areaType = "table";
                reqData.rows = resultRows;
                requestApi.save({
                    data: reqData,
                    success: (data) => {
                        this.pubMessage.copySuccess();
                    }
                });
            }
        })
    }

    close() {
        this.setState({ showModal: false });
    }

    treeSelectEvent(key, item) {
        let props = this.props;
        window.rolePk = key;
        requestApi.query({
            data : {
                pkRole : key
            },
            success: (data) => {
                this.setState({
                    showRight: true
                });
                let busiRows = [];
                let deptRows = [];
                if (data){
                    let returnData = null;
                    if(data[window.bodyCode]){
                        returnData = data[window.bodyCode];
                    }else if(data[window.body1Code]){
                        returnData = data[window.body1Code];
                    }
                    returnData&&returnData.rows.forEach((row) => {
                        if (row.values.keyword.value.indexOf('busiuser') > -1){
                            busiRows.push(row);
                        } else if (row.values.keyword.value.indexOf('pk_deptdoc') > -1){
                            deptRows.push(row);
                        }
                        if (row.values.keyword.value.indexOf('issamedept') > -1){
                            props.form.setFormItemsValue(window.body2Code, {
                                'issamedept' : {
                                    value: row.values.pk_user.value == 'true'?true:false
                                },
                            }, false);
                        } else if (row.values.keyword.value.indexOf('isall') > -1){
                            props.form.setFormItemsValue(window.body2Code, {
                                'isall' : {
                                    value: row.values.pk_user.value == 'true'?true:false
                                },
                            }, false);
                        } else {
                            props.form.setFormItemsValue(window.body2Code, {
                                issamedept : {
                                    value: false
                                },
                                isall : {
                                    value: false
                                }
                            }, false);
                        }
                    })
                } else {
                    props.form.setFormItemsValue(window.body2Code, {
                        issamedept : {
                            value: false
                        },
                        isall : {
                            value: false
                        }
                    }, false);
                }
                props.editTable.setTableData(window.bodyCode, {
                    "rows" : busiRows
                });
                props.editTable.setTableData(window.body1Code, {
                    "rows" : deptRows
                });
            }
        });
    }

    render() {
        const { table, form, modal } = this.props;
        let { createForm } = form;
        let { createSimpleTable} = table;
        let props = this.props;
        let multiLang = this.props.MutiInit.getIntl(2011); //this.moduleId
        let { createModal } = modal;

        return (
            <ProfileStyle
                layout="treeTable"
                {...this.props}
                id='auth-agent'
            >
                <ProfileHead
                    // "201101DLSQ-0001": "授权代理设置"
                    title={multiLang && multiLang.get('201101DLSQ-0001')}
                    refreshButtonEvent={refreshButtonClick.bind(this)} 
                    status = { this.state.status }
                >
                    <HeadCenterCustom>
                        <div style={{ width : '204px'}}><BusinessUnitTreeRef
                            disabled = {this.state.disableOrg}
                            value = {this.state.fianceRef}
                            onChange={(...a) => {
                                if (a && a.length > 0){
                                    this.queryRole(a[0].refpk);
                                    this.setState({ fianceRef : a[0]});
                                }
                            }}
                            queryCondition = {function () {
                                return {
                                    TreeRefActionExt:'nccloud.web.erm.action.ref.sqlbuilder.BusinessUnitTreeRefBuilder',
                                    appcode : props.getSearchParam('c')
                                }
                            }}
                        /></div>
                    </HeadCenterCustom>

                    <ButtonGroup
                        area="page_header"
                        buttonLimit="3"
                        buttonEvent={buttonClick.bind(this)}
                    />
                </ProfileHead>
                <ProfileBody>
                    <BodyLeft>
                        <SyncTree
                            areaId="tree1"
                            onSelectEve={
                                this.treeSelectEvent.bind(this)
                            }
                            disabledSearch={this.state.disabledSearch}
                            /* checkable = { true }
                            onCheckEve = { this.onCheckEve } */
                        />
                    </BodyLeft>

                    <BodyRight>
                        <EmptyArea
                            // "201101DLSQ-0002": "特殊代理"
                            title={multiLang && multiLang.get('201101DLSQ-0002')}
                        >
                            {createForm(window.body2Code, {

                            })}
                        </EmptyArea>

                        <EditTable
                            areaId="SqdlDept"
                            showCheck = {false}
                            // "201101DLSQ-0003": "可代理部门"
                            title={multiLang && multiLang.get('201101DLSQ-0003')}
                            onAfterEvent={afterEvent.bind(this)}
                        >
                            <ButtonGroup
                                area="list_head1"
                                buttonEvent={buttonClick.bind(this)}
                            />
                        </EditTable>
                        <EditTable
                            areaId="Sqdlr"
                            showCheck = {false}
                            // "201101DLSQ-0004": "可代理人员"
                            title={multiLang && multiLang.get('201101DLSQ-0004')}
                            onAfterEvent={afterEvent.bind(this)}
                        >
                            <ButtonGroup
                                area="list_head"
                                buttonEvent={buttonClick.bind(this)}
                            />
                        </EditTable>
                        {
                           multiLang && createModal('copy',{
                                title:  multiLang.get('201101DLSQ-0005'),// 复制规则到
                                content: <div className="area-content" >
                                    {createSimpleTable('copyModal', {
                                        onAfterEvent: afterEvent,
                                        showCheck:true,
                                        showIndex:true
                                    })}
                                </div>, //弹框内容，可以是字符串或dom
                                beSureBtnClick: this.copy.bind(this), //点击确定按钮事件
                                /* cancelBtnClick: this.close.bind(this), //取消按钮事件回调
                                closeModalEve: this.close.bind(this), //关闭按钮事件回调 */
                                userControl:false,  // 点确定按钮后，是否自动关闭弹出框.true:手动关。false:自动关
                                size:'lg', //  模态框大小 sm/lg/xlg
                                noFooter : false, //是否需要底部按钮,默认true
                                rightBtnName :  multiLang.get('2011-0002'), //左侧按钮名称,默认关闭
                                leftBtnName : multiLang.get('2011-0003'), //右侧按钮名称， 默认确认
                            })
                        }
                    </BodyRight>
                </ProfileBody>
            </ProfileStyle>


        )
    }

}

AuthAgentConfig = createPage({
    mutiLangCode: '2011'
})(AuthAgentConfig);


ReactDOM.render(<AuthAgentConfig/>, document.querySelector('#app'));